﻿using System;
using System.Runtime.InteropServices;
using System.Threading;
using System.Windows.Forms;

namespace SiriRobot
{
    internal static class Program
    {
        static Mutex _mutex = new Mutex(true, "SiriRobot.WithPlugins");

        /// <summary>
        /// 应用程序的主入口点。
        /// </summary>
        [STAThread]
        static void Main()
        {
            if (_mutex.WaitOne(TimeSpan.Zero, true))
            {
                Application.EnableVisualStyles();
                Application.SetCompatibleTextRenderingDefault(false);
                Application.Run(new FrmMain());
                _mutex.ReleaseMutex();
            }
            else
            {
                ActivatePreviousInstance();
            }
        }

        private static void ActivatePreviousInstance()
        {
            NativeMethods.PostMessage((IntPtr)NativeMethods.HWND_BROADCAST, NativeMethods.WM_ACTIVATE_PREVIOUS_INSTANCE, IntPtr.Zero, IntPtr.Zero);
        }
    }

    static class NativeMethods
    {
        public const int HWND_BROADCAST = 0xffff;
        public static readonly int WM_ACTIVATE_PREVIOUS_INSTANCE = RegisterWindowMessage("WM_ACTIVATE_PREVIOUS_INSTANCE");

        [DllImport("user32.dll", CharSet = CharSet.Unicode)]
        public static extern int RegisterWindowMessage(string message);

        [DllImport("user32.dll", SetLastError = true)]
        public static extern bool PostMessage(IntPtr hWnd, int Msg, IntPtr wParam, IntPtr lParam);
    }
}
